# D115 Admin Tags
from django import template
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.db.models import get_model

register = template.Library()

@register.filter
def mcount(m):
    try:
        return m._default_manager.count()
    except:
        return ''

# [("Container1", ["app1.model1", "app2.model2"]), ]

def grep_model(app_list, mnamed):
    mname = mnamed.lower().replace('.', '/') + '/'
    for app in app_list:
        for model in app['models']:
            if model['admin_url'] == mname:
                try:
                    model['model'] = get_model(*mnamed.split('.'))
                except:
                    pass
                return model

@register.filter
def regroup_apps(app_list):
    new_list = []
    cdefs = settings.ADMIN_CONTAINERS if hasattr(settings, 'ADMIN_CONTAINERS') else []
    passed = []
    for container in cdefs:
        models = []
        for model in container[1]:
            m = grep_model(app_list, model)
            if m:
                models.append(m)
                passed.append(m['admin_url'])
        app_dict = {'app_url':'#', 'models':models, 'has_module_perms':True, 'name':container[0]}
        if len(container) > 2:
            app_dict.update(container[2])
        new_list.append(app_dict)
    # Collect left-overs
    lo_models = []
    for app in app_list:
        for model in app['models']:
            if not model['admin_url'] in passed:
                lo_models.append(model)
    if lo_models:
        new_list.append({'app_url':'#', 'models':lo_models, 'has_module_perms':True, 'name':_("Others")})
    return new_list
